//Converts the xml doc to a DOM Node object
function loadXMLDoc(dname)
{
    xhttp=new XMLHttpRequest();
	xhttp.open("GET",dname,false);
	xhttp.send("");
	return xhttp.responseXML;
}


function getDataFromXML(row, col) {
    
    var path = "/guncase/gun[" + row + "]/" + translation(col);

    xml.setProperty("SelectionLanguage", "XPath");
    //returns nodes on the corresponding path from the root
    var nodes = xml.selectNodes(path);
        
    return nodes[0].childNodes[0].nodeValue
}

//Creates Table containing the row with the corresponding index
function printTable(index){
    var str = openTable();
    xml = loadXMLDoc("guncase.xml");
    str += createTableHeader();
 
    str += insertRow(getDataFromXML(index, 1), getDataFromXML(index, 2), getDataFromXML(index, 3), getDataFromXML(index, 4));
    
    str += closeTable();
    
    document.getElementById("table").innerHTML=str;
}

//Creates and prints the table with all the data in the XML file
function printAllTable() {
    var str = openTable();
    var size = getSize();
    str += createTableHeader();
    xml = loadXMLDoc("guncase.xml");
    var i = 1;
    for (i = 1; i <= size; i++) {
        str += insertRow(getDataFromXML(i, 1), getDataFromXML(i, 2), getDataFromXML(i, 3), getDataFromXML(i, 4));
    }
    
    str += closeTable();
    
    document.getElementById("table").innerHTML = str;
}

//Converts the column index to the name of the column
function translation( index ) {
    switch ( index ) {
        case 1: return "maker";
            break;
        case 2: return "model";
            break;
        case 3: return "caliber";
            break;
        case 4: return "action";
            break;
        default: return "error";
    }
}

//Retrieves the number of guns in the XML document
function getXMLLength() {
    xml = loadXMLDoc("guncase.xml");
    document.getElementById("size").innerHTML = xml.childNodes[3].childNodes.length
    return xml.childNodes[3].childNodes.length;
}

//Returns HTML table tag
function openTable(){
    return "<table>";
}

//Returns HTML close table tag
function closeTable() {
    return "</table>";
}

//Returns the HTML code for the table header
function createTableHeader() {
    return "<tr> <th>Maker</th> <th>Model</th> <th>Caliber</th> <th>Action</th> </tr>";
}

//Returns the HTML code for the row with the given column data 
function insertRow(maker, model, caliber, action) {
    return "<tr> <td>" + maker + "</td> <td>" + model + "</td> <td>" + caliber + "</td> <td>" + action + "</td> </tr>";
}

//Reads the hidden size field which contains the number of guns in the XML document
function getSize() {
    return document.getElementById("size").innerHTML;
}
